<template>
  <div class="cart">
    <header class="cart_header">
      <van-nav-bar title="购物车" />
    </header>
    <main style="margin-top: 8px;">
      <van-cell-group inset style="margin-top: 8px;" v-for="item in cartStore?.dataSource" :key="item?.id">
        <van-card style="background-color: #fff;" :price="item?.subtotal" :title="item?.name"
          :thumb="`/api${item?.mainImage}`">
          <template #desc>
            <p class="van-multi-ellipsis--l3">{{ item?.description }}</p>
          </template>
          <template #tags>
            <van-tag style="margin-top: 4px; margin-bottom: 4px;" plain type="primary">{{ item?.productNo }}</van-tag>
          </template>
          <template #footer>
            <van-space align="center">
              <van-stepper integer :default-value="item?.productQty" theme="round" button-size="22" disable-input
                @plus="handlePlus(item)" @minus="handleMinus(item)" />
              <van-button size="mini" type="danger" icon="delete-o" @click="handleDelete(item)"></van-button>
            </van-space>
          </template>
        </van-card>
      </van-cell-group>
    </main>
    <footer v-if="cartStore?.dataSource?.length > 0">
      <van-action-bar style="margin-bottom: 50px;">
        <van-action-bar-icon icon="bar-chart-o" text="总数量" :badge="cartStore?.total" :badge-props="{ showZero: false }" />
        <van-action-bar-icon icon="balance-o" text="总价格" :badge="cartStore?.totalPrice"
          :badge-props="{ showZero: false }" />
        <van-action-bar-button type="danger" text="立即下单" @click="showBottom = true" />
      </van-action-bar>
    </footer>
    <van-empty description="购物车空空如也，快去将菜品加入购物车吧！"  v-if="!cartStore?.dataSource?.length"/>
    <van-popup v-model:show="showBottom" position="bottom" closeable :style="{ height: '40%' }">
      <div style="box-sizing: border-box; padding-top: 8px;">
        <h4 style="text-align: center;">生成订单</h4>
        <van-form @submit="onSubmit" style="margin-top: 4px;">
          <van-cell-group inset>
            <van-field label="总数量" :model-value="cartStore?.total" readonly />
            <van-field label="总价格" :model-value="cartStore?.totalPrice" readonly />
            <van-field v-model="remark" type="text" name="remark" label="备注" placeholder="请输入备注" />
          </van-cell-group>
          <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
              提交
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>
    <section style="height: 120px;"></section>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { showToast, showConfirmDialog } from 'vant';
import { deleteCart, editCart } from '@/apis/cart';
import { addOrder, payOrder } from '@/apis/order';
import { useCartStore } from '@/stores/cart';

const merchantId = localStorage.getItem('merchantId');
const cartStore = useCartStore();
const remark = ref('')
const showBottom = ref(false);


const handlePlus = async (item) => {
  try {
    const { code, msg } = await editCart({
      id: item?.id,
      productQty: item?.productQty + 1,
    });
    if (code === 200) {
      showToast(`加购${item?.name}成功`);
      cartStore?.init();
      return;
    }
    showToast(msg)

  } catch (error) {
    console.log(error, 'error');
  }
};

const handleMinus = async (item) => {
  try {
    const { code, msg } = await editCart({
      id: item?.id,
      productQty: item?.productQty - 1,
    });
    if (code === 200) {
      showToast(`减购${item?.name}成功`);
      cartStore?.init();
      return;
    }
    showToast(msg)

  } catch (error) {
    console.log(error, 'error');
  }

}

const handleDelete = (item) => {

  showConfirmDialog({
    title: `确定要删除${item?.productQty}${item?.productUnit}${item?.name}吗？`,
  })
    .then(async () => {
      try {
        const { code, msg } = await deleteCart(item?.id);
        if (code === 200) {
          showToast(`删除${item?.name}成功`);
          cartStore?.init();
          return;
        }
        showToast(msg)
      } catch (error) {
        console.log(error, 'delete-cart-error');

      }
    })
    .catch(() => {

    });

};

const onSubmit = async (values) => {
  try {
    const { data: id, code, msg } = await addOrder({merchantId,remark: values?.remark });
    if (code === 200) {
      const { code, msg } = await payOrder({ id,status: 1 });
      if (code === 200) {
        showToast('操作成功');
        showBottom.value = false;
        cartStore?.init();
        return;
      }
      showToast(msg);

      return;
    }
    showToast(msg);
  } catch (error) {
    console.log(error, 'order-error');

  }

}

onMounted(() => {
  cartStore?.init();
});
</script>

<style lang="less" scoped></style>
